package com.yunfeng.supercall.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalDb.DbUpdateListener;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.yunfeng.supercall.BuildConfig;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.bean.ChatMessageBean;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;

public class ChatMessageManager extends ManagerBaseIface {

	private static final Map<String, List<ChatMessageBean>> MESSAGES;
	static {
		MESSAGES = new HashMap<String, List<ChatMessageBean>>();
	}
	private FinalDb mFinalDb;
	private UserBean mUser;
	private static ChatMessageManager sChatMessageManager;
	private SuperFriendsManager mFriendsManager;
	Context context;
	public static ChatMessageManager getInstance(Context context) {
		synchronized (ChatMessageManager.class) {
			if (sChatMessageManager == null) {
				sChatMessageManager = new ChatMessageManager(
						context.getApplicationContext());
			}
		}

		return sChatMessageManager;
	}

	protected ChatMessageManager(Context context) {
		this.context = context;
		mUser = BaseActivity.getUser(context);
		mFriendsManager = (SuperFriendsManager) ManagerFactory
				.createManager(SuperFriendsBean.class);
		try {
			mSelfCode = mUser.getVo_id();
		} catch(NullPointerException e) {

		}
		try {
			mFinalDb = FinalDb.create(context, "chat" + mUser.getUserid(),
					BuildConfig.DEBUG, 2, new DbUpdateListener() {

				@Override
				public void onUpgrade(SQLiteDatabase arg0, int arg1,
						int arg2) {
					// TODO Auto-generated method stub
					try {
						arg0.execSQL("alter table"
								+ "com_yunfeng_supercall_bean_ChatMessage"
								+ " add column unreadCount int");
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}catch (NullPointerException e) {

		}
	}

	private String mSelfCode;


	public ArrayList<ChatMessageBean> findAllChatMessages() {
		ArrayList<ChatMessageBean> messages = null;
		try {
			messages = new ArrayList<ChatMessageBean>(mFinalDb.findAll(ChatMessageBean.class));
			// TODO Auto-generated catch block
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (messages == null) {
			messages = new ArrayList<ChatMessageBean>();
		}
		return messages;
	}




	public List<ChatMessageBean> findChatMessages(ContactsBaseBean base) {
		String name = "";
		if (base instanceof SuperFriendsBean) {
			name = ((SuperFriendsBean) base).getVo_id();
		} else {
			name = base.getPhone();
		}
		List<ChatMessageBean> messages = MESSAGES.get(name);
		if (messages == null) {
			try {
				messages = mFinalDb.findAllByWhere(ChatMessageBean.class,
						"(msgFrom='" + name + "' and msgTo= '" + mSelfCode
						+ "') or (msgFrom='" + mSelfCode
						+ "' and msgTo = '" + name + "')");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			MESSAGES.put(name, messages);
		}
		if (messages == null) {
			messages = new ArrayList<ChatMessageBean>();
			MESSAGES.put(name, messages);
		}
		return messages;
	}

	public void clear(ContactsBaseBean base) {
		String name = "";
		if (base instanceof SuperFriendsBean) {
			name = ((SuperFriendsBean) base).getVo_id();
		} else {
			name = base.getPhone();
		}
		mFinalDb.deleteByWhere(ChatMessageBean.class, "(msgFrom='" + name
				+ "' and msgTo= '" + mSelfCode + "') or (msgFrom='" + mSelfCode
				+ "' and msgTo = '" + name + "')");
		List<ChatMessageBean> chatMessages = findChatMessages(base);
		chatMessages.clear();
	}

	public void putMessages(ContactsBaseBean base, ChatMessageBean message) {

		//创建存放数据的ContentValues对象  
		ContentValues values = new ContentValues();  
		//像ContentValues中存放数据  
		values.put("idr", message.getId() + "");  
		/*values.put("chatType",message.getChatType() + "");*/
		values.put("chatType",message.getChatType());
		values.put("content", message.getContent() + "");
		values.put("msgFrom",message.getMsgFrom() + "");
		values.put("msgId",message.getMsgId() + "");
		values.put("msgTo",message.getMsgTo() + "");
		values.put("receiveTime",message.getReceiveTime() + "");
		values.put("voiceLength", message.getVoiceLenth() + "");
		values.put("isread","1");
		values.put("UnreadCount","0");

		DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(context, "db", 2);  
		SQLiteDatabase db3 = dbHelper3.getWritableDatabase();  
		//数据库执行插入命令  
		long i = db3.insert("UCSMessage", null, values);  
		Log.i("TAG", "service " + i);

		if(db3 != null) {
			db3.close();
			db3 = null;
		}

		if(dbHelper3 != null) {
			dbHelper3.close();
			dbHelper3 = null;
		}

		try {


			//		Log.i("yun", "msg" + base.getNick_name());
			//下面我觉得没用
			List<ChatMessageBean> chatMessages = findChatMessages(base);
			Log.i("yun", "message" + base.getPhone());
			if (chatMessages != null) {
				Log.i("yun", "message3" + base.getPhone());
				if (!chatMessages.contains(message)) {
					base.setUnread(true);
					int count = base.getUnreadCount();
					count = count + 1;
					base.setUnreadCount(count);
					findChatMessages(base).add(message);
					mFriendsManager.updateFriends((SuperFriendsBean) base);
					mFinalDb.save(message);
				}
			}
		} catch(Exception e) {

		}
		
		DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(context, "db", 2);
		SuperFriendsBean mSuperFriendsBean = mDatabaseHelperForChattingMap.getSuperFriendsBeanByVoId(message.getMsgFrom());
		mDatabaseHelperForChattingMap.incReadCount(mSuperFriendsBean.getUserid() + "");
		if(mDatabaseHelperForChattingMap != null) {
			mDatabaseHelperForChattingMap.close();
		}
	}
	class CustumRunnable implements Runnable {
		String key;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Session session = Session.getSession();
			session.init(context, true);
			//			mSession.getFriendDetailNew(getApplicationContext(), userBean.getUserid(), mSuperFriendsBean.getUserid(), new ResultReceiver<SuperFriendsBean>() {

			session.searchUser(context, key, new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean args) {
					// TODO Auto-generated method stub
					DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(context, "db", 2);  
					dbHelper3.insertSuperFrined(args);
					if(dbHelper3 != null) {
						dbHelper3.close();
						dbHelper3 = null;
					}
				}

			});

		}

	}
	/*Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Session session = Session.getSession();
			session.init(context, true);
//			mSession.getFriendDetailNew(getApplicationContext(), userBean.getUserid(), mSuperFriendsBean.getUserid(), new ResultReceiver<SuperFriendsBean>() {

			session.searchUser(context, result, mUserBean.getType(), resUserId, mUserBean.getLat(), mUserBean.getLng(), new ResultReceiver<SuperFriendsBean>() {

				@Override
				public void onResult(boolean last, SuperFriendsBean args) {
					// TODO Auto-generated method stub

				}

			});

		}

	};
	 */	


	public void updateMessages(ChatMessageBean chatMessage) {
		mFinalDb.update(chatMessage);
	}

	public void deleteMessages(ChatMessageBean chatMessage, ContactsBaseBean base) {
		List<ChatMessageBean> chatMessages = findChatMessages(base);
		if (chatMessages != null) {
			chatMessages.remove(chatMessage);
		}
		mFinalDb.delete(chatMessage);

	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		super.clear();
		Iterator iterator = MESSAGES.keySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry entry = (Map.Entry) iterator.next();
			Object key = entry.getKey();
			List<ChatMessageBean> val = (List<ChatMessageBean>) entry.getValue();
			val.clear();
		}
		MESSAGES.clear();
	}

}
